package com.mazaiting.manager.controller;

import com.mazaiting.common.core.ex.exceptions.BaseException;
import com.mazaiting.common.core.ex.exceptions.EmptyObjectException;
import com.mazaiting.manager.constant.WebConstant;
import com.mazaiting.manager.domain.form.UserForm;
import com.mazaiting.manager.domain.query.UserPageQuery;
import com.mazaiting.manager.domain.vo.user.*;
import com.mazaiting.manager.dto.UserAuthDTO;
import com.mazaiting.manager.service.ISysUserService;
import com.mazaiting.manager.utils.ExcelUtil;
import com.mazaiting.mybatisplus.domain.vo.BasePageVO;
import com.mazaiting.web.auth.security.annotation.PrePermission;
import com.mazaiting.web.constant.MediaTypeExtend;
import com.mazaiting.web.domain.SingleResult;
import com.mazaiting.web.utils.HttpUtil;
import com.mazaiting.web.utils.WebUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 用户控制器
 *
 * @author mazaiting
 * @since 2022-09-17
 */
@Slf4j
@RestController
@RequestMapping("manager/v1/users")
@RequiredArgsConstructor
public class SysUserController {

    private final ISysUserService sysUserService;

    /**
     * 获取当前用户的登录信息
     *
     * @return 登录信息
     */
    @GetMapping("/me")
    public LoginUserVO getLoginUserInfo() throws EmptyObjectException {
        return sysUserService.getLoginUserInfo();
    }

    /**
     * 用户分页列表
     *
     * @param queryParams 查询参数
     * @return 用户列表
     */
    @PrePermission("sys:user:query")
    @GetMapping("/pages")
    public BasePageVO<SysUserVO> listUserPages(UserPageQuery queryParams) {
        return sysUserService.listUserPages(queryParams);
    }

    /**
     * 用户表单数据
     *
     * @param userId 用户 ID
     * @return 用户详情数据
     */
    @PrePermission("sys:user:update")
    @GetMapping("/{userId}")
    public UserDetailVO getUserDetail(@PathVariable Long userId) throws EmptyObjectException {
        return sysUserService.getUserDetail(userId);
    }

    /**
     * 新增用户
     *
     * @param userForm 用户表单
     * @return true: 新增成功; false: 新增失败
     */
    @PrePermission("sys:user:add")
    @PostMapping
    public boolean save(@Validated UserForm userForm) throws BaseException {
        return sysUserService.save(userForm);
    }

    /**
     * 修改用户
     *
     * @param userForm 用户表单数据
     * @return true: 修改成功; false: 修改失败
     */
    @PrePermission("sys:user:update")
    @PutMapping
    public boolean update(@Validated UserForm userForm) throws BaseException {
        return sysUserService.update(userForm);
    }

    /**
     * 删除用户
     *
     * @param ids 用户 ID 列表. 用户ID，多个以英文逗号(,)分割
     * @return true: 删除成功; false: 删除失败
     */
    @PrePermission("sys:user:delete")
    @DeleteMapping("/{ids}")
    public boolean delete(@PathVariable String ids) throws BaseException {
        return sysUserService.delete(ids);
    }

    /**
     * 修改用户密码
     *
     * @param userId   用户 ID
     * @param password 密码
     * @return true: 修改成功; false: 修改失败
     */
    @PrePermission("sys:user:update_pwd")
    @PatchMapping(value = "/{userId}/password")
    public boolean updatePassword(@PathVariable Long userId, @RequestParam String password) throws EmptyObjectException {
        return sysUserService.updatePassword(userId, password);
    }

    /**
     * 修改用户状态
     *
     * @param userId  用户 ID
     * @param enabled 用户是否可用
     * @return true: 修改成功; false: 修改失败
     */
    @PrePermission("sys:user:update_enabled")
    @PatchMapping(value = "/{userId}/enabled")
    public boolean updateUserEnabled(@PathVariable Long userId, @RequestParam Boolean enabled) throws EmptyObjectException {
        return sysUserService.updateEnabled(userId, enabled);
    }

    /**
     * 根据用户名获取认证信息
     *
     * @param username 用户名
     * @return 用户认证信息
     */
    @GetMapping("/username/{username}")
    public UserAuthDTO getAuthInfoByUsername(@PathVariable String username) throws EmptyObjectException {
        return sysUserService.getAuthInfoByUsername(username);
    }

    /**
     * 根据手机号获取认证信息
     *
     * @param mobile 手机号
     * @return 用户认证信息
     */
    @GetMapping("/mobile/{mobile}")
    public UserAuthDTO getAuthInfoByMobile(@PathVariable String mobile) throws EmptyObjectException {
        return sysUserService.getAuthInfoByMobile(mobile);
    }

    /**
     * 导出用户
     *
     * @param queryParams 查询参数
     * @param response    响应
     */
    @PrePermission("sys:user:export")
    @GetMapping("/export")
    public void exportUsers(UserPageQuery queryParams, HttpServletResponse response) throws IOException {
        // 设置下载属性
        HttpUtil.setDownloadProp(response, WebConstant.EXPORT_FILE_USER_LIST, MediaTypeExtend.APPLICATION_VND_XLSX);
        // 根据查询条件导出数据
        List<UserExportVO> exportUserList = sysUserService.listExportUsers(queryParams);
        ExcelUtil.export(response.getOutputStream(), "用户列表", exportUserList, UserExportVO.class);
    }

    /**
     * 用户导入模板下载
     *
     * @param response 响应
     */
    @PrePermission("sys:user:import")
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = WebConstant.TEMPLATE_USER;
        HttpUtil.setDownloadProp(response, fileName, MediaTypeExtend.APPLICATION_VND_XLSX);
        // 模板文件路径
        String fileClassPath = WebConstant.FOLDER_EXCEL_TEMPLATES + File.separator + fileName;
        InputStream is = WebUtil.getResource(fileClassPath);
        ExcelUtil.export(response.getOutputStream(), is);
    }


    /**
     * 导入用户
     *
     * @param userImportVO 用户导入视图
     * @return 异常信息
     */
    @PrePermission("sys:user:import")
    @PostMapping("/import")
    public SingleResult importUsers(UserImportVO userImportVO) throws Exception {
        // @RequestParam("roleIds") 只在上传文件时可用
//    public StringResponseVO importUsers(Long deptId, @RequestParam("roleIds") List<Long> roleIds, MultipartFile file) throws Exception {
//        return sysUserService.importUsers(new UserImportVO(userImport1VO.getDeptId(), userImport1VO.getRoleIds(), file));
        return sysUserService.importUsers(userImportVO);
    }


}
